package ffdata.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import com.google.common.io.Files;

import ffdata.scraping.Consts;
import ffmvc.model.JSONHolder;

public class FileUtils {
	public static void printHrefs(Set<String> hrefs) {
		try {
			File file = new File(Consts.getHrefsLocation());
			Files.write(Joiner.on("\n").join(hrefs), file,
					StandardCharsets.UTF_8);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static Set<String> getPlayerHrefsFromFile() {
		Set<String> lineList = null;
		try {
			File file = new File(Consts.getHrefsLocation());
			String fileContents = Files.toString(file, StandardCharsets.UTF_8);
			Iterable<String> line = Splitter.on('\n').trimResults()
					.omitEmptyStrings().split(fileContents);
			lineList = Sets.newHashSet(line);

		} catch (IOException e) {
			e.printStackTrace();
		}
		return lineList;
	}

	public static void printScrapedData(JSONHolder holder, File file) {

		StringBuilder onePlayer = new StringBuilder("href:").append(
				holder.getUrl()).append("\n");
		onePlayer.append("player_history:").append(holder.getPlayerHistory())
				.append("\n");
		onePlayer.append("player_stats:").append(holder.getPlayerStats())
				.append("\n");
		onePlayer.append("player:").append(holder.getPlayer()).append("\n");
		onePlayer.append("############\n");
		try {
			if (onePlayer.toString().contains("player_history:null")
					|| onePlayer.toString().contains("player_stats:null")
					|| onePlayer.toString().contains("player:null")) {
				return;
			} else {
				Files.append(onePlayer.toString(), file, StandardCharsets.UTF_8);
			}

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static boolean isFileEmpty(String path) {

		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(path));
			if (br.readLine() == null) {
				return true;
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (br != null)
					br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return false;

	}

	// get name of file in format scrapings_currentdate.txt
	public static String getNameForScrapingsFile() {

		DateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
		// get current date time with Date()
		Date date = new Date();
		StringBuilder name = new StringBuilder("scrapings_").append(
				dateFormat.format(date)).append(".txt");
		return name.toString();

	}

	public static File getLatestScrapingFile() {

		List<File> results = new ArrayList<File>();

		File[] files = new File(Consts.getScrapingsLocation()).listFiles();
		// If this pathname does not denote a directory, then listFiles()
		// returns null.

		for (File file : files) {
			if (file.isFile() && file.getName().startsWith("scrapings_")) {
				results.add(file);
			}
		}

		if (results.size() == 0)
			return null;
		File lastModifiedFile = results.get(0);
		for (int i = 1; i < results.size(); i++) {
			if (lastModifiedFile.lastModified() < results.get(i).lastModified()) {
				lastModifiedFile = results.get(i);
			}
		}

		return lastModifiedFile;
	}

	public static Set<String> getUnvisitedHrefs() {
		List<String> lineList = null;
		Set<String> visited = new HashSet<String>();
		try {
			File file = getLatestScrapingFile();
			if (file == null) {
				return null;
			}
			// first the missing urls
			String fileContents = Files.toString(file, StandardCharsets.UTF_8);
			Iterable<String> lines = Splitter.on('\n').trimResults()
					.omitEmptyStrings().split(fileContents);
			lineList = Lists.newArrayList(lines);
			for (String line : lineList) {
				if (line.startsWith("href:")) {
					String href = line.substring("href:".length());
					visited.add(href);

				}
			}

		} catch (IOException e) {
			e.printStackTrace();
		}

		Set<String> all = getPlayerHrefsFromFile();
		all.removeAll(visited);
		return all;
	}

	public static List<JSONHolder> loadScrapings() {

		File file = getLatestScrapingFile();
		String fileContents;
		List<JSONHolder> holders = new ArrayList<JSONHolder>();
		try {
			fileContents = Files.toString(file, StandardCharsets.UTF_8);
			Iterable<String> stats = Splitter.on("############\n")
					.trimResults().omitEmptyStrings().split(fileContents);

			for (String stat : stats) {
				Iterable<String> subLines = Splitter.on("\n").trimResults()
						.omitEmptyStrings().split(stat);
				JSONHolder holder = new JSONHolder();
				for (String subLine : subLines) {

					if (subLine.startsWith("href:")) {
						String substring = subLine.substring("href:".length());
						holder.setUrl(substring);
					}
					if (subLine.startsWith("player_history:")) {
						String substring = subLine.substring("player_history:"
								.length());
						holder.setPlayerHistory(new JSONObject(substring));
					}
					if (subLine.startsWith("player_stats:")) {
						String substring = subLine.substring("player_stats:"
								.length());
						holder.setPlayerStats(new JSONObject(substring));
					}
					if (subLine.startsWith("player:")) {
						String substring = subLine
								.substring("player:".length());
						holder.setPlayer(new JSONObject(substring));
					}
				}
				holders.add(holder);
			}

		} catch (IOException e) {
			e.printStackTrace();
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return holders;

	}

}
